let express = require('express');
let router = express.Router();
let request = require('request');

function productList() {
    // product
}

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
    next();
});

function jsonData(code, d) {
    return ({error_code: code, data: d});
}

function formatDateTime(timestamp) {
    let date = new Date(timestamp);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = date.getDate() + ' ';
    let h = date.getHours() + ':';
    let m = date.getMinutes() + ':';
    let s = date.getSeconds();
    return Y + M + D + h + m + s;
}

let thisHost = 'https://zp.wifi.com';
//thisHost = 'https://testapi-b.wifi.com';

router.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    /*判断get还是post*/
    if (JSON.stringify(req.body) !== "{}") {
        request.post(thisHost + req.path, {
            form: req.body
        }, function (error, res2, body) {
            if (!error && res2.statusCode === 200) {
                res.json(JSON.parse(body));
            } else {
                res.json(jsonData(-1, {}));
            }
        });
    } else {
        request.get(thisHost + req.path, {
            qs: req.query
        }, function (error, res2, body) {
            if (!error && res2.statusCode === 200) {
                res.json(JSON.parse(body));
            } else {
                res.json(jsonData(-1, {}));
            }
        });
    }

});


module.exports = router;
